package com.nova.android.tvlauncher.interfaces.factory

import com.nova.android.tvlauncher.interfaces.IMainManager
import java.util.ServiceLoader
import kotlin.jvm.java

object ServiceFactory {
    private val cache = mutableMapOf<Class<*>, Any>()

    @Suppress("UNCHECKED_CAST")
    fun <T> getService(serviceClass: Class<T>): T {
        return cache.getOrPut(serviceClass) {
            val loader = ServiceLoader.load(serviceClass, serviceClass.classLoader)
            val service = loader.firstOrNull() ?: throw IllegalStateException("No provider found for ${serviceClass.name}")
            service
        } as T
    }
}

fun main(){
    //调用示例
    //val mainManager = ServiceFactory.getService(IMainManager::class.java)
    //val anotherManager = ServiceFactory.getService(IAnotherManager::class.java)
}